<template>
  <el-card>
    <template #header>
      <h3>添加商品</h3>
    </template>
    <!-- 添加商品表单 -->
    <el-form
      :model="goodsForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goodsForm.name" placeholder="商品名称"></el-input>
      </el-form-item>
      <el-form-item label="商品分类" prop="cate">
        <el-select v-model="goodsForm.cate" placeholder="请选择商品分类">
          <el-option
            v-for="item in cateData"
            :key="item.cateName"
            :label="item.cateName"
            :value="item.cateName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number
          v-model="goodsForm.price"
          :min="0"
          :max="100"
          label="描述文字"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:5000/goods/goods_img_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品描述" prop="desc">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          v-model="goodsForm.desc"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >添加商品</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { goodsAllCate, addGoods } from '../../api/goods.js'
export default {
  data() {
    return {
      goodsForm: {
        name: '',
        cate: '',
        price: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cate: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [{ required: true, message: '请输入价格', trigger: 'change' }],
        desc: [{ required: true, message: '请具体描述', trigger: 'blur' }]
      },
      imageUrl: '',
      cateData: []
    }
  },
  created() {
    this.getAllCate()
  },
  methods: {
    async getAllCate() {
      const { categories } = await goodsAllCate()
      // console.log(categories)
      this.cateData = categories
      // console.log(this.cateData, 11)
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          // 当表单验证通过，则可以发起请求
          if (this.imageUrl === '') {
            this.$message.error('请上传商品图片')
          } else {
            const data = await addGoods({
              name: this.goodsForm.name,
              category: this.goodsForm.cate,
              price: this.goodsForm.price,
              imgUrl: this.uploadUrl,
              goodsDesc: this.goodsForm.desc
            })
            if (data.code === 0) {
              this.$message({
                type: 'success',
                message: data.msg
              })
              this.resetForm(formName)
              this.$router.push('/goods/list')
            }
          }
        } else {
          this.$message.error('请按要求填写！！！')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.uploadUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // 判断当前图片的type类型是否在上面的数组中
      // arr.includes(file.type)
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="less" scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
.el-input {
  width: 200px;
}
/deep/.el-textarea {
  width: 280px;
}
</style>
